package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type promotionalImage struct {
	iPromotionalImage store.IPromotionalImage
}

var PromotionalImage = &promotionalImage{
	iPromotionalImage: postgres.PromotionalImage,
}

func (a *promotionalImage) init() func() {
	return func() {}
}

func (a *promotionalImage) onEvent(*event.Data) {}

// Create 创建
func (a *promotionalImage) Create(ctx context.Context, in *model.PromotionalImageCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildPromotionalImage(in)
	_, err = a.iPromotionalImage.Create(ctx, c)
	return err
}

// Update 更新
func (a *promotionalImage) Update(ctx context.Context, in *model.PromotionalImageUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.ImageUrl != nil {
		dict["image_url"] = in.ImageUrl
	}

	if in.Weight != nil {
		dict["weight"] = in.Weight
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iPromotionalImage.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *promotionalImage) Delete(ctx context.Context, in *model.PromotionalImageDeleteRequest) error {
	return a.iPromotionalImage.Delete(ctx, in.Id)
}

// List 列表查询
func (a *promotionalImage) List(ctx context.Context, in *model.PromotionalImageListRequest) (*model.PromotionalImageListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.PromotionalImage
		out   = &model.PromotionalImageListResponse{}
	)

	if total, list, err = a.iPromotionalImage.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.PromotionalImagesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *promotionalImage) Find(ctx context.Context, in *model.PromotionalImageInfoRequest) (*model.PromotionalImageInfo, error) {
	var (
		err  error
		data *entity.PromotionalImage
		out  = &model.PromotionalImageInfo{}
	)

	if data, err = a.iPromotionalImage.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.PromotionalImageEntityToDto(data)
	return out, nil
}

// buildPromotionalImage 构建创建数据现场
func buildPromotionalImage(in *model.PromotionalImageCreateRequest) *entity.PromotionalImage {
	// todo: check the entity is required
	return &entity.PromotionalImage{

		Name: in.Name,

		Desc: in.Desc,

		ImageUrl: in.ImageUrl,

		Weight: in.Weight,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
